<?php

namespace app\service;

use app\model\Dict;
use app\model\DictCate;
use app\validate\DictCateValidate;
use think\annotation\Inject;
use think\exception\ValidateException;

class DictCateService
{
    /**
     * @Inject()
     * @var DictCate
     */
    protected $dictCateModel;

    /**
     * @Inject()
     * @var Dict
     */
    protected $dictModel;

    /**
     * 获取分类数
     * @return array
     */
    public function getDictCateTree()
    {
        $list = $this->dictCateModel->getDictCateList();
        if ($list['code'] != 0) {
            return $list;
        }

        $tree = makeMenuTree($list['data']->toArray(), 'pid');
        return dataReturn(0, 'success', $tree);
    }

    /**
     * 获取所有的字典分类
     * @return array
     */
    public function getAllDictCate()
    {
        return $this->dictCateModel->getDictCateList();
    }

    /**
     * 添加字典分类
     * @param $param
     * @return array
     */
    public function addDictCate($param)
    {
        try {

            validate(DictCateValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        return $this->dictCateModel->addDictCate($param);
    }

    /**
     * 编辑字典分类
     * @param $param
     * @return array
     */
    public function editDictCate($param)
    {
        try {

            validate(DictCateValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-3, $e->getError());
        }

        return $this->dictCateModel->editDictCate($param);
    }

    /**
     * 删除字典分类
     * @param $id
     * @return array
     */
    public function delDictCate($id)
    {
        $res = $this->dictModel->getDictByCateId($id);
        if ($res['code'] != 0) {
            return $res;
        }

        if (!empty($res['data'])) {
            return dataReturn(-3, '该分类下有数据，不可删除');
        }

        return $this->dictCateModel->delDictCate($id);
    }
}